import gulp from 'gulp';
import gulpSass from 'gulp-sass';
import * as sass from 'sass';
import cleanCss from 'gulp-clean-css';
import { rollup } from 'rollup';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import terser from '@rollup/plugin-terser';
// import { deleteAsync } from 'del';
import { envrc } from './envrc.js';

const scss = gulpSass(sass);

const env = envrc[process.env.APP_MODE]
console.log(env);

// function clean() {
//     return deleteAsync([env.assetsDir]);
// }

function styles() {
    let next = gulp.src([
        'src/main.scss',
        'src/other.scss',
    ]);
    next = next.pipe(scss().on('error', scss.logError));
    if (env.compress) {
        next = next.pipe(cleanCss());
    }
    next = next.pipe(gulp.dest(env.output.cssPath));
    return next;
}

function rollupBuild() {
    const plugins = [
        resolve(),
        commonjs(),
        babel({
            presets: ['@babel/preset-env'],
            exclude: 'node_modules/**'
        }),
    ];
    if (env.compress) {
        plugins.push(terser());
    }
    const config = {
        input: [
            'src/index.js',
            'src/about.js',
            'src/download/download.js'
        ],
        output: {
            dir: env.output.jsPath,
            format: 'es',
            // format: 'iife',
            entryFileNames: '[name].js',
            sourcemap: env.sourcemap,
        },
        plugins
    };
    let next = rollup(config);
    next = next.then(bundle => bundle.write(config.output));
    return next;
}

function scripts(done) {
    rollupBuild().then(() => {
        done();
    }).catch((e) => {
        console.error(e);
        done();
    });
}

function watch() {
    gulp.watch(['src/**/*.scss'], styles);
    gulp.watch(['src/**/*.js'], scripts);
}

export {
    // clean,
    styles,
    scripts,
    watch,
}

const build = gulp.parallel(
    // clean,
    styles,
    scripts,
);


const dev = gulp.series(build, watch);

export default env.mode === 'test' ? dev : build;
